package com.uairobot.bill.freeswitch.controller;

import java.util.HashMap;

import org.freeswitch.esl.client.inbound.Client;
import org.freeswitch.esl.client.inbound.InboundConnectionFailure;
import org.freeswitch.esl.client.transport.message.EslMessage;

import com.jfinal.core.Controller;
import com.uairobot.bill.freeswitch.util.FsUtil;
import com.uairobot.bill.freeswitch.vo.JsonBean;

import lombok.extern.slf4j.Slf4j;

/**
 * @author bill robot
 * @date 2020年2月7日_下午3:35:06 
 * @version 1.0 
 * @desc
 */
@Slf4j
public class FsController extends Controller {
  public void connectThis() {
    Client fsClient = FsUtil.connectThis();
    boolean canSend = fsClient.canSend();
    fsClient.close();
    JsonBean<Boolean> jsonBean = new JsonBean<>(canSend);
    if (!canSend) {
      jsonBean.setCode(-1);
    }
    renderJson(jsonBean);
  }

  public void connect(String ip, int port, String pswd) {
    Client fsClient = new Client();
    // 连接freeswitch
    boolean canSend = false;
    try {
      fsClient.connect(ip, port, pswd, 10);
      canSend = fsClient.canSend();
    } catch (InboundConnectionFailure e) {
      fsClient.close();
      log.error("连接freeswitch失败:ip:{},port:{}", ip, port);
      e.printStackTrace();
      JsonBean<String> jsonBean = new JsonBean<>(-1, e.getMessage());
      renderJson(jsonBean);
      return;
    } finally {
      fsClient.close();
    }

    JsonBean<Boolean> jsonBean = new JsonBean<>(canSend);
    if (!canSend) {
      jsonBean.setCode(-1);
    }
    renderJson(jsonBean);
  }

  public void sendSyncApiCommand(String ip, int port, String pswd, String cmd, String param1, String param2) {
    Client fsClient = null;
    if (ip != null) {
      fsClient = new Client();
      // 连接freeswitch
      try {
        fsClient.connect(ip, port, pswd, 10);
      } catch (InboundConnectionFailure e) {
        fsClient.close();
        log.error("连接freeswitch失败:ip:{},port:{}", ip, port);
        e.printStackTrace();
        JsonBean<String> jsonBean = new JsonBean<>(-1, e.getMessage());
        renderJson(jsonBean);
        return;
      }
    } else {
      // freeswitch event socket client
      fsClient = FsUtil.connectThis();
    }
    log.info("sendSyncApiCommand {},{},{}", cmd, param1, param2);
    EslMessage eslMessage = fsClient.sendSyncApiCommand(cmd, param1 + " " + param2);
    fsClient.close();
    String bodyLines = eslMessage.getBodyLines().toString();
    log.info("bodyLines : " + bodyLines);
    HashMap<String, String> hashMap = new HashMap<>(1);
    hashMap.put("bodyLines", bodyLines);
    JsonBean<HashMap<String, String>> jsonBean = new JsonBean<>(hashMap);
    renderJson(jsonBean);
  }
}
